﻿namespace OneWorks.Utils.Export
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Reflection;
    using NPOI.HSSF.UserModel;
    using NPOI.SS.UserModel;

    public class ExeclExportFile<T> : BaseExportFile<T> where T : class
    {
        public ExeclExportFile(List<T> data, string savePath)
            : base(data, savePath)
        {
            SavePath = savePath;
            Datas = data;
        }

        public override string ToExport()
        {           
            using (MemoryStream memoryStream = new MemoryStream())
            {
                IWorkbook workbook = new HSSFWorkbook();
                ISheet sheet = workbook.CreateSheet("sheet1");
                ProDictionary = GetDictionary();
                int rowIndex = 0;
                int columnIndex = 0;
                IRow headRow = sheet.CreateRow(rowIndex);         
                foreach (var attribute in ProDictionary)
                {
                    ICell iCell = headRow.CreateCell(columnIndex);                    
                    iCell.SetCellValue(attribute.Value.DisplayName);
                    columnIndex++;
                }
                foreach (var data in Datas)
                {
                    columnIndex = 0;
                    rowIndex++;
                    IRow row = sheet.CreateRow(rowIndex);
                    foreach (PropertyInfo dataInfo in data.GetType().GetProperties())
                    {
                        ICell iCell = row.CreateCell(columnIndex);

                        iCell.SetCellValue(Convert.ToString(dataInfo.GetValue(data, null)));
                        columnIndex++;
                    }
                }

                workbook.Write(memoryStream);
                memoryStream.Flush();
                memoryStream.Position = 0;
                ExportFile(memoryStream);
            }
            return SavePath;
        }

        private void ExportFile(MemoryStream stream)
        {
            using (stream)
            {
                using (FileStream fileStream = new FileStream(SavePath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite))
                {
                    stream.WriteTo(fileStream);
                    stream.Close();
                    fileStream.Close();
                    fileStream.Close();
                }
            }
        }
    }
}
